package com.example.iread.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListPopupWindow;
import android.widget.TextView;

import com.example.iread.MainActivity;
import com.example.iread.R;
import com.example.iread.adapter.BookListPagerAdapter;
import com.example.iread.bean.BookBean;
import com.example.iread.bean.ResponseBean;
import com.example.iread.bean.TypeBean;
import com.example.iread.exception.MyException;
import com.example.iread.http.BookApi;
import com.example.iread.http.CategoryApi;
import com.example.iread.http.ChapterApi;
import com.example.iread.service.AudioPlayService;
import com.example.iread.util.DensityUtil;
import com.example.iread.util.FloatWindowUtil;
import com.example.iread.util.GsonUtil;
import com.example.iread.util.HttpUtil;
import com.example.iread.util.MediaPlayerUtil;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class BookListActivity extends AppCompatActivity {

    // === ViewPager动画相关
    private static final float MAX_SCALE = 1.0F;
    private static final float MIN_SCALE = 0.85f;

    // === log
    private static final String TAG = "SoRiya";

    // === Handler相关
    private Handler updateViewHandler;

    private final int UPDATE_VIEW_ICON = 0;

    private final int UPDATE_VIEW_TITLE = 1;

    private final int UPDATE_VIEW_COVER = 2;

    // === 权限请求相关
    private final int REQUEST_CODE_FLOATING_WINDOW = 0;

    // === View
    private TextView tv_type_title;
    private ImageView iv_type_icon;

    // ===
    private int typeId;

    private int bookId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);

        Intent intent = getIntent();
        typeId = intent.getIntExtra("typeId", 0);

        // 消息处理器
        updateViewHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == UPDATE_VIEW_ICON) {
                    Bitmap bitmap = (Bitmap) msg.obj;
                    iv_type_icon.setImageBitmap(bitmap);
                }
                if (msg.what == UPDATE_VIEW_TITLE) {
                    tv_type_title.setText(msg.obj.toString());
                }
            }
        };

        initBasicData();

        initBookList();

        // 关闭按钮
        View btn_book_list_close = findViewById(R.id.btn_book_list_close);
        btn_book_list_close.setOnClickListener(v -> {
            finish();
        });

        ImageButton btn_more_handler = findViewById(R.id.btn_more_handler);

        ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(this, R.layout.item_select, new String[]{"Home", "Profile"});
        listPopupWindow.setAdapter(stringArrayAdapter);
        listPopupWindow.setAnchorView(btn_more_handler);
        listPopupWindow.setModal(true);
        listPopupWindow.setWidth(DensityUtil.dpToPx(this, 80));
        listPopupWindow.setOnItemClickListener((adapterView, view, i, l) -> {
            Intent toIntent = new Intent(this, MainActivity.class);
            toIntent.putExtra("page", i);
            toIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(toIntent);
            finish();
        });
        btn_more_handler.setOnClickListener(v -> {
            listPopupWindow.show();
        });
    }

    private void initBasicData() {
        tv_type_title = findViewById(R.id.tv_type_title);
        iv_type_icon = findViewById(R.id.iv_type_icon);

        CategoryApi.getById(typeId, res -> {
            TypeBean typeBean = GsonUtil.parseObject(res.data, TypeBean.class);
            Message msgTitle = new Message();
            msgTitle.what = UPDATE_VIEW_TITLE;
            msgTitle.obj = typeBean.typeName;
            updateViewHandler.sendMessage(msgTitle);
            new Thread(() -> {
                try {
                    URL url = new URL(HttpUtil.getImageUrl(typeBean.typeIcon));
                    Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
                    Message msgIcon = new Message();
                    msgIcon.what = UPDATE_VIEW_ICON;
                    msgIcon.obj = bitmap;
                    updateViewHandler.sendMessage(msgIcon);
                } catch (Exception e) {
                    throw new MyException(500, e.getMessage());
                }
            }).start();
        });
    }

    private void initBookList() {
        TextView tv_book_name = findViewById(R.id.tv_book_name);
        TextView tv_book_author = findViewById(R.id.tv_book_author);
        TextView tv_book_chapters = findViewById(R.id.tv_book_chapters);

        new Thread(() -> {
            ResponseBean res = BookApi.getByTypeId(1, 100, typeId);
            String s = new GsonBuilder().serializeNulls().create().toJson(res.data);
            String rows;
            try {
                JSONObject jsonObject = new JSONObject(s);
                rows = jsonObject.getJSONArray("rows").toString();
            } catch (JSONException e) {
                throw new MyException(500, e.getMessage());
            }

            Log.i(TAG, "rows: " + rows);

            List<BookBean> bookBeans = new GsonBuilder().serializeNulls().create().fromJson(rows, TypeToken.getParameterized(List.class, BookBean.class).getType());

            List<ImageView> imageViews = new ArrayList<>();
            for (BookBean item : bookBeans) {
                // 创建ImageView
                ShapeableImageView imageView = new ShapeableImageView(this);
                // 设置宽高
                imageView.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                ));
                Handler handler = new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        if (msg.what == UPDATE_VIEW_COVER) {
                            Bitmap bitmap = (Bitmap) msg.obj;
                            imageView.setImageBitmap(bitmap);
                        }
                    }
                };
                // 设置图片资源
                new Thread(() -> {
                    String cover = item.cover;
                    try {
                        InputStream inputStream = new URL(HttpUtil.getImageUrl(cover)).openStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        Message message = new Message();
                        message.what = UPDATE_VIEW_COVER;
                        message.obj = bitmap;
                        handler.sendMessage(message);
                    } catch (IOException e) {
                        throw new MyException(500, e.getMessage());
                    }
                }).start();
//                imageView.setImageResource(item);
                // 设置填充方式
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                // 设置缩放
                imageView.setScaleX(MIN_SCALE);
                imageView.setScaleY(MIN_SCALE);
                // 设置高度
                imageView.setElevation(DensityUtil.dpToPx(this, 10));
                // 点击事件
                imageView.setOnClickListener(v -> {
                    Intent intent = new Intent(this, BookInfoActivity.class);
                    intent.putExtra("bookId", item.id);
                    startActivity(intent);
                });
                imageViews.add(imageView);
            }

            ViewPager vp_book_list = findViewById(R.id.vp_book_list);
            Button btn_book_read = findViewById(R.id.btn_book_read);
//            Button btn_book_play = findViewById(R.id.btn_book_play);

            // 设置设配器
            BookListPagerAdapter bookListPagerAdapter = new BookListPagerAdapter(this, imageViews);
            updateViewHandler.post(() -> {
                if (bookBeans.size() > 0) {
                    tv_book_name.setText(bookBeans.get(0).bookName);
                    tv_book_author.setText(bookBeans.get(0).author);
                    bookId = bookBeans.get(0).id;
                    ChapterApi.getCountByBookId(bookId, r -> {
                        updateViewHandler.post(() -> {
                            tv_book_chapters.setText(((Number) r.data).intValue() + " Chapters");
                        });
                    });
                }

                vp_book_list.setAdapter(bookListPagerAdapter);

                // 滑动动画
                vp_book_list.setPageTransformer(true, (view, position) -> {
                    if (position >= -1 && position <= 1) {
                        // 将要显示的大的View
                        float scaleFactor = MIN_SCALE + (1 - Math.abs(position)) * (MAX_SCALE - MIN_SCALE);
                        view.setScaleX(scaleFactor);
                        view.setScaleY(scaleFactor);
                    } else {
                        view.setScaleX(MIN_SCALE);
                        view.setScaleY(MIN_SCALE);
                    }
                });

                // 预加载数量
                vp_book_list.setOffscreenPageLimit(2);
            });

            // 设置监听
            vp_book_list.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

                @Override
                public void onPageSelected(int position) {
                    String bookName = bookBeans.get(position).bookName;
                    String author = bookBeans.get(position).author;
                    bookId = bookBeans.get(position).id;
                    ChapterApi.getCountByBookId(bookId, res -> {
                        updateViewHandler.post(() -> {
                            tv_book_name.setText(bookName);
                            tv_book_author.setText(author);
                            tv_book_chapters.setText(((Number) res.data).intValue() + " Chapters");
                        });
                    });
                }

                @Override
                public void onPageScrollStateChanged(int state) {}
            });

            btn_book_read.setOnClickListener(v -> {
                Intent intent = new Intent(this, BookInfoActivity.class);
                intent.putExtra("bookId", bookId);
                startActivity(intent);
            });

//            btn_book_play.setOnClickListener(v -> {
//                Intent intent = new Intent(this, AudioPlayService.class);
//                intent.putExtra("url", url);
//                startService(intent);
//                FloatWindowUtil.getInstance().show(this);
//            });

        }).start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_FLOATING_WINDOW) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.fromParts("package", getPackageName(), null));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        if (resultCode == REQUEST_CODE_FLOATING_WINDOW) {
            if (Settings.canDrawOverlays(this)) {
                // 用户授予了悬浮窗口权限，执行相应的操作
                // ...
            } else {
                // 用户未授予悬浮窗口权限，可能需要提示用户或执行其他操作
                // ...
            }
        }
    }
}